package com.wisemoresystem.seal.action.mac.install;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.wisemoresystem.seal.base.action.ProjBaseAction;
import com.wisemoresystem.seal.base.tip.Tip;
import com.wisemoresystem.seal.model.t_mac;
import com.wisemoresystem.seal.service.MacMoveLogService;
import com.wisemoresystem.seal.service.MacService;
import com.wisemoresystem.seal.util.json.JsonTools;

/**
 * 录入
 * 
 * @author Administrator
 *
 */
@Controller("macInstall")
@Scope("prototype")
@RequestMapping("/ix/mac/install")
public class MacInstallAction extends ProjBaseAction {

	@Autowired
	private MacService macService;
	@Autowired
	private MacMoveLogService macLogService;

	@RequestMapping("/add_form")
	public ModelAndView add_form() {

		ModelAndView mv = new ModelAndView("/jsp/mac/install/add_form");
		return mv;
	}

	/**
	 * 印控仪添加
	 * 
	 * @param mac_codes
	 *            印控仪编号
	 * @param note
	 *            添加备注
	 * @return
	 */
	@RequestMapping("/add")
	public ModelAndView add(String mac_codes, String note) {

		ModelAndView mv = new ModelAndView("redirect:add_form.htm");

		// 校验设备编号
		Map<String, Object> map = JsonTools
				.jsonStrToMap(check_is_have(mac_codes));
		if ("false".equals(map.get("result"))) {
			this.setTipMsg(map.get("msg") + "", Tip.Type.error);
			return mv;
		}
		String[] macCode = mac_codes.split(",");
		macLogService.saveMacs(macCode, note);
		logT.logH("印控仪录入", t_mac.class, null);

		this.setTipMsg("录入成功!", Tip.Type.success);
		return mv;
	}

	/**
	 * 检查印控仪唯一性
	 * 
	 * @param mac_codes
	 *            印控仪编号
	 * @return
	 */
	@RequestMapping("/check_is_have")
	@ResponseBody
	public String check_is_have(String mac_codes) {

		Map<String, String> map = new HashMap<String, String>();
		map.put("result", "true");
		map.put("msg", "");
		String[] macCode = mac_codes.split(",");
		for (String code : macCode) {
			if (code.length() > 9) {
				map.put("result", "false");
				map.put("msg", "录入失败!单个编号的长度不能大于 9.");
			}
		}
		if ("true".equals(map.get("result"))) {
			List<String> retMacCodes = macService.checkIsHave(macCode);
			if (retMacCodes.size() > 0) {
				map.put("result", "false");
				map.put("msg", "录入失败!已经存在设备编号:" + JsonTools.toJson(retMacCodes));
			}
		}

		return JsonTools.toJson(map);
	}
}
